<?php
class PreparedStatement
{
    private $con;               // Used to store the MySQL connection
    private $values;            // The array in which all ints and strings will be stored
    private $query_string;      // The SQL statement which has to be executed
    private $cur_number;
    private $cur_value;

    function __construct($query) {
        $this->query_string = $query; // Set the user-input query in query_string
    }

    private function connect() {
        $this->con = mysql_connect(db_host, db_username, db_password);  // Connect to the database and store it in: "con"
        mysql_select_db(db_database, $this->con);                       // Select the database with the connection: "con"
    }

    private function disconnect() {
        mysql_close($this->con); // Close the mysql connection: "con"
    }

    private function check_value() {
        $this->cur_value = $this->clean_user_input($this->cur_value);
        if(strpos($this->query_string, "?") < stristr($this->query_string, "VALUES"))
            return "`" . $this->cur_value . "`";
        else
            return "'" . $this->cur_value . "'";
    }

    function clean_user_input($input){
        if (get_magic_quotes_gpc())
            $clean = mysql_real_escape_string(stripslashes($input));
        else
            $clean = mysql_real_escape_string($input);
        return $clean;
    }

    private function real_execute() {
            $q = mysql_query($this->query_string);
            $this->disconnect();
            return $q;
    }

    public function execute() {
        $this->connect();
        if(count($this->values) == substr_count($this->query_string, "?") && count($this->values) > 0) {
            foreach($this->values as $this->cur_number => $this->cur_value) {
                $this->query_string = substr_replace($this->query_string, $this->check_value(), strpos($this->query_string,"?"), 1);
            }
            return $this->real_execute();
        }
        elseif(count($this->values) == 0 && substr_count($this->query_string, "?") == 0) {
            return $this->real_execute();
        }
        else {
            echo "PreparedStatement could not be executed, " . count($this->values) . " values set, " . substr_count($this->query_string, "?") . " needed.";
        }
    }

    public function setInt($value) {
        $this->values[] += $value;
    }

    public function setString($value) {
        $this->values[] .= $value;
    }
}
?>